# 计算Legendre多项式及Gauss积分点
# 使用AI辅助

import sympy as sp
import sympy.integrals.quadrature

x = sp.symbols('x')

P_list = []
P_prime_list = []
P_list.append(1)
P_list.append(x)

for n in range(2,6):
    P = ((2*n-1)*x*P_list[n-1] - (n-1)*P_list[n-2]) / n
    P_list.append(P.simplify())

for n in range(6):
    P_prime_list.append(sp.diff(P_list[n],x))

#print(P_list)
#print(P_prime_list)

for n in range(6):
    print(f'{n} order Legendre Poly: {P_list[n]}')
    
    # Method 1: Symbolic computation
    print("\nMethod 1 (Symbolic):")
    roots_dict = sp.roots(P_list[n])
    for xi, multiplicity in roots_dict.items():
        wi = 2/((1-xi**2)*(P_prime_list[n].subs(x,xi))**2)
        print(f'xi: {xi.evalf():.3f}, wi: {wi.evalf():.3f}')
    
    # Method 2: SymPy's quadrature
    nodes, weights = sympy.integrals.quadrature.gauss_legendre(n, 3)
    print("\nMethod 2 (Quadrature):")
    for xi, wi in zip(nodes, weights):
        print(f'xi: {float(xi):.3f}, wi: {float(wi):.3f}')
    
    print('\n' + '='*50 + '\n')
